<?php namespace App\Admin\Supplier\Supplier\Listeners;

use Input;
use App\Core\Exceptions\InputError;
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Service\Listeners\CreateListener as Base;

use App\Admin\Access\User\Repository as UserRepository;

class CreateListener extends Base {
    
    public function onCreateSaved(){
        $this->createUser();
    }
    
    private function createUser(){
        $username = Input::get('username');
        $password = Input::get('password');
        $name = Input::get('name');
        $contact_name = Input::get('contact_name');
        $contact_tel = Input::get('contact_tel');
        if(!$username || !$password){
            throw new InputError('非法操作');
        }
        if(!$this->checkUsername($username)){
            throw new InputError('用户名已存在');
        }
        $data = [
            'username' => $username,
            'nickname' => $name,
            'name' => $contact_name,
            'phone' => $contact_tel,
            'type' => '1',
            'role_id' => '11'
        ];
        //密码处理
        $data['saltcode'] = rand(10000, 99999);
        $data['password'] = md5($password.$data['saltcode']);
        //登录信息初始化
        $data['login_error_count'] = '0';
        $data['islocked'] = '0';
        $user = with(new UserRepository())->create($data);
        $client = $this->service->createModel;
        $client->admin_id = $user->user_id;
        $client->save();
    }
    
    private function checkUsername($username){
        return !with(new UserRepository())->addCriteria(new FixedCriteria('username', $username))->count() > 0;
    }
}